import uuid
from fastapi import APIRouter, Depends, UploadFile, Form, HTTPException, File
from fastapi.responses import JSONResponse
from pathlib import Path
from sqlalchemy.orm import Session
from typing import Annotated
from typing import Optional

from app import models
from app.db.database import get_db
from app.models.harp import Harps, Sozluk
from app.schemas.harp_schemas import SozlukResponse
from app.schemas.harp_schemas import create_harp, harp_update
from app.utils.setting import Settings

settings = Settings()


def get_all_harps(db: Session):
    return db.query(Harps).all()


def get_harp_with_id(id: int, db: Session):
    return db.query(Harps).filter(Harps.id == id).first()


async def create_harp_service(db: Session, harp_data: dict):
    db_harp = Harps(
        harp_name=harp_data["harp_name"],
        harp_type=harp_data["harp_type"],
        harp_desc=harp_data["harp_desc"],
        audio_url=harp_data["audio_url"],
        is_bax=harp_data["is_bax"]
    )
    db.add(db_harp)
    db.commit()
    db.refresh(db_harp)
    return db_harp


async def register_new_harp(data: harp_update, db: Session = Depends(get_db)):
    try:
        file_ext = Path(audio_url.filename).suffix
        unique_filename = f"{uuid.uuid4()}{file_ext}"
        file_location = settings.upload_dir / unique_filename
        # 保存文件
        with open(file_location, "wb+") as file_object:
            file_object.write(audio_url.file.read())
        relative_path = f"{settings.base_url}uploads/{unique_filename}"
        # 准备数据
        harp_data = {
            "harp_name": harp_name,
            "harp_type": harp_type,
            "harp_desc": harp_desc,
            "audio_url": relative_path,  # 存储相对路径
            "is_bax": is_bax.lower() == "true"  # 转换为布尔值
        }
        return await create_harp_service(db, data)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文件上传失败: {str(e)}")


upload_dir = Path("./uploads")
upload_dir.mkdir(exist_ok=True)


async def update_harp(
        id: int,
        harp_name: str,
        harp_type: str,
        harp_desc: str,
        audio_url: Optional[UploadFile] = None,
        is_bax: str = "false",
        db: Session = Depends(get_db)
):
    # 函数实现...

    try:
        harp = db.query(Harps).filter(Harps.id == id).first()
        if not harp:
            raise HTTPException(status_code=404, detail="Harp 不存在！")

        if audio_url:
            # 删除旧文件
            if harp.audio_url:
                old_path = harp.audio_url.replace(settings.base_url, "").lstrip("/")
                old_file = Path(old_path)
                if old_file.exists():
                    old_file.unlink()

            # 保存新文件
            file_ext = Path(audio_url.filename).suffix
            unique_filename = f"{uuid.uuid4()}{file_ext}"
            file_location = upload_dir / unique_filename

            with open(file_location, "wb+") as f:
                f.write(audio_url.file.read())
            harp.audio_url = f"{settings.base_url}uploads/{unique_filename}"

        # 更新其他字段
        harp.harp_name = harp_name
        harp.harp_type = harp_type
        harp.harp_desc = harp_desc
        harp.is_bax = is_bax.lower() == "true"

        db.commit()
        db.refresh(harp)
        return JSONResponse(content=f"id为（{harp.id}）的更新成功！", status_code=200)
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新失败: {str(e)}")


# sozluk

def get_all_sozluk(db: Session):
    return db.query(Sozluk).all()


def get_sozluk_with_id(id: int, db: Session):
    return db.query(Sozluk).filter(Sozluk.id == id).first()


async def create_sozluk(
        harp_id: int = Form(...),
        sozluk_data_1: str = Form(...),
        sozluk_data_1_audio: Optional[UploadFile] = File(None),
        sozluk_data_2: str = Form(...),
        sozluk_data_2_audio: Optional[UploadFile] = File(None),
        sozluk_data_3: str = Form(...),
        sozluk_data_3_audio: Optional[UploadFile] = File(None),
        sozluk_data_4: str = Form(...),
        sozluk_data_4_audio: Optional[UploadFile] = File(None),
        db: Session = Depends(get_db)
):
    try:
        # 处理所有音频文件
        sozluk_data_1_audio_url = await handle_audio_upload(sozluk_data_1_audio, "1")
        sozluk_data_2_audio_url = await handle_audio_upload(sozluk_data_2_audio, "2")
        sozluk_data_3_audio_url = await handle_audio_upload(sozluk_data_3_audio, "3")
        sozluk_data_4_audio_url = await handle_audio_upload(sozluk_data_4_audio, "4")

        # 准备数据
        sozluk_data = {
            "harp_id": harp_id,
            "sozluk_data_1": sozluk_data_1,
            "sozluk_data_1_audio_url": sozluk_data_1_audio_url,
            "sozluk_data_2": sozluk_data_2,
            "sozluk_data_2_audio_url": sozluk_data_2_audio_url,
            "sozluk_data_3": sozluk_data_3,
            "sozluk_data_3_audio_url": sozluk_data_3_audio_url,
            "sozluk_data_4": sozluk_data_4,
            "sozluk_data_4_audio_url": sozluk_data_4_audio_url
        }

        # 创建记录
        db_sozluk = Sozluk(**sozluk_data)
        db.add(db_sozluk)
        db.commit()
        db.refresh(db_sozluk)

        return SozlukResponse.from_orm(db_sozluk)

    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"创建Sozluk记录失败: {str(e)}")
